Exerccos 8

########### Galileu estava Certo?

init.h = c(600, 700, 800, 950, 1100, 1300, 1500)
h.d = c(253, 337, 395, 451, 495, 534, 573)
## Modelo linear
mod1 <- lm(h.d~init.h)
## Modelo de parabola
mod2 <- lm(h.d~init.h+I(init.h^2))
anova(mod2)
### Polinomio de terceiro grau
mod3 <- lm(h.d~init.h+I(init.h^2)+I(init.h^3))
### Comparao de resultados:
anova(mod1,mod2)
anova(mod2, mod3)
### Resumo dos resultados
summary(mod3) ###R-squared: 0.9987, p-value: 2.662e-05 
##coeficientes
cf2 <- coef(mod2)
cf3 <- coef(mod3)
cf2
cf3
## Grafico com as 3 linhas previstas
plot(h.d~init.h)
abline(mod1)
curve(cf2[1]+cf2[2]*x+cf2[3]*x^2, add=T, col="blue")
curve(cf3[1]+cf3[2]*x+cf3[3]*x^2+cf3[4]*x^3, add=T, col="red") ## A curva se ajusta de maneira muito mais aproximada dos resultados observados

############# Massa dos bebs ao nascer
bebes <- read.table(file="babies.txt", header=TRUE, sep="")
head(bebes)
str(bebes)

##convertendo parity em logico
bebes$parity <- as.logical(bebes$parity)
## Testando regresses lineares simples bwt contra cada varivel:
ges<- lm(bebes$bwt~bebes$gestation)
par<- lm(bebes$bwt~bebes$parity)
age<- lm(bebes$bwt~bebes$age)
hei<- lm(bebes$bwt~bebes$height)
wei<- lm(bebes$bwt~bebes$weight)
smo<- lm(bebes$bwt~bebes$smoke)
anova(ges,par,age,hei,wei,smo)

## "gestation" e "parity" possuem o menor valor da soma dos quadrados dos desvios e sero escolhidos para integrar o modelo.  
## Uma inspeo visual nas variveis que podem ser usadas como preditoras: 
pairs(bebes[-c(8:9)])## weigth e smoke tambm podero ser usadas.
## Analisando o modelo com essas 4 variveis
anova(lm(bwt~gestation+parity+weight+smoke, data=bebes)) ## Gestation (p=0.0271226) e smoke (p=0.0004633), possuem os menores valoes de p e sero usados para testar as interaes
## Testando interaes de 1a ordem.
anova(lm(bwt~gestation+parity+weight+smoke+gestation*smoke,data=bebes)) ## interao  significante (p= 0.0214755)
anova(lm(bwt~gestation+parity+weight+smoke+gestation*parity,data=bebes))
anova(lm(bwt~gestation+parity+weight+smoke+gestation*weight,data=bebes))
anova(lm(bwt~gestation+parity+weight+smoke+smoke*parity,data=bebes)) ## interao parity:smoke significativa (p=0.0041909)
anova(lm(bwt~gestation+parity+weight+smoke+smoke*weight,data=bebes))
anova(lm(bwt~gestation+parity+weight+smoke+smoke*,data=bebes))
### Melhores modelos:
Bebes.m1 = anova(lm(bwt~gestation+parity+weight+smoke+gestation*smoke,data=bebes))
Bebes.m2 = anova(lm(bwt~gestation+parity+weight+smoke+smoke*parity,data=bebes))